#!/bin/bash

# 临时禁用IPv4数据包重定向发送
echo 0 > /proc/sys/net/ipv4/conf/all/send_redirects
echo 0 > /proc/sys/net/ipv4/conf/default/send_redirects

# 临时禁用IPv6数据包重定向接收
echo 0 > /proc/sys/net/ipv6/conf/all/accept_redirects 2>/dev/null
echo 0 > /proc/sys/net/ipv6/conf/default/accept_redirects 2>/dev/null

# 永久禁用IPv4 send_redirects
if grep -q "^net.ipv4.conf.all.send_redirects" /etc/sysctl.conf; then
    sed -i 's/^net.ipv4.conf.all.send_redirects.*/net.ipv4.conf.all.send_redirects=0/' /etc/sysctl.conf
else
    echo "net.ipv4.conf.all.send_redirects=0" >> /etc/sysctl.conf
fi

if grep -q "^net.ipv4.conf.default.send_redirects" /etc/sysctl.conf; then
    sed -i 's/^net.ipv4.conf.default.send_redirects.*/net.ipv4.conf.default.send_redirects=0/' /etc/sysctl.conf
else
    echo "net.ipv4.conf.default.send_redirects=0" >> /etc/sysctl.conf
fi

# 永久禁用IPv6 accept_redirects
if grep -q "^net.ipv6.conf.all.accept_redirects" /etc/sysctl.conf; then
    sed -i 's/^net.ipv6.conf.all.accept_redirects.*/net.ipv6.conf.all.accept_redirects=0/' /etc/sysctl.conf
else
    echo "net.ipv6.conf.all.accept_redirects=0" >> /etc/sysctl.conf
fi

if grep -q "^net.ipv6.conf.default.accept_redirects" /etc/sysctl.conf; then
    sed -i 's/^net.ipv6.conf.default.accept_redirects.*/net.ipv6.conf.default.accept_redirects=0/' /etc/sysctl.conf
else
    echo "net.ipv6.conf.default.accept_redirects=0" >> /etc/sysctl.conf
fi

# 应用配置
sysctl -p >/dev/null 2>&1

echo "数据包重定向禁用配置完成"